package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.UserFeign;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author：杨鹏
 * @Package：com.bwie.auth.service.impl
 * @Project：yp_zhoukao723
 * @name：AuthServiceImpl
 * @Date：2024/7/23 9:27
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result<User> login(User user) {

        if (StringUtils.isAllBlank(user.getUserName(),user.getUserPwd())){
            return Result.error("手机号或密码不能为空");
        }

        Result<User> login = userFeign.login(user);
        User data = login.getData();

        if (data == null){
            return Result.error("手机号不存在");
        }

        if (!data.getUserPwd().equals(user.getUserPwd())){
            return Result.error("密码错误");
        }

        String userKey = UUID.randomUUID().toString().replace("-", "");

        Map<String, Object> map = new HashMap<>();

        map.put(JwtConstants.USER_KEY,userKey);

        String token = JwtUtils.createToken(map);

        data.setToken(token);

        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(data),
                TokenConstants.EXPIRATION, TimeUnit.MINUTES);

        return Result.success(data);
    }

    @Override
    public Result<User> info() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return Result.success(JSONObject.parseObject(user, User.class));
    }

    @Override
    public void logout() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        redisTemplate.delete(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }
}
